import * as mars3d from 'mars3d';
import * as Cesium from 'mars3d-cesium';
import WKT from 'terraformer-wkt-parser';

// 根据用户偏好设置图层
const getUserPreferencesLayers = (baseMapName: any, noteName: any) => {
  const baseMaps: any = {
    天地图影像: {
      name: '底图',
      type: 'tdt',
      layer: 'img_d',
      pid: 1,
      id: 2,
      zIndex: 2,
    },
    ArcGIS影像: {
      pid: 10,
      name: 'ArcGIS影像',
      icon: 'http://mars3d.cn/img/basemaps/esriWorldImagery.png',
      type: 'xyz',
      url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
      enablePickFeatures: false,
      id: 21,
      templateValues: {
        dataServer: '//data.mars3d.cn',
        gltfServerUrl: '//data.mars3d.cn/gltf',
      },
      opacity: 1,
      zIndex: 15,
    },
    星图影像: {
      name: '底图',
      type: 'xyz',
      url: 'https://tiles{s}.geovisearth.com/base/v1/img/{z}/{x}/{y}?token=82455ef06c72bb3a35bbb4d7d05fd9eceb96a94dc942a056b8feb0e5928ed96f',
      subdomains: '123',
    },
    微软影像: {
      pid: 10,
      name: '微软影像',
      icon: 'http://mars3d.cn/img/basemaps/bingAerial.png',
      type: 'bing',
      layer: 'Aerial',
      id: 22,
      opacity: 1,
      zIndex: 16,
    },
    高德影像: {
      name: '底图',
      type: 'gaode',
      layer: 'img_d',
      pid: 7,
      id: 8,
      zIndex: 6,
    },
    百度影像: {
      name: '底图',
      type: 'baidu',
      layer: 'img_d',
      pid: 12,
      id: 13,
      zIndex: 9,
    },
    百度电子: {
      pid: 10,
      name: '百度电子',
      icon: 'http://mars3d.cn/img/basemaps/bd-vec.png',
      type: 'baidu',
      layer: 'vec',
      id: 15,
      opacity: 1,
      zIndex: 11,
    },
  };
  const noteMaps: any = {
    天地图注记: {
      name: '注记',
      type: 'tdt',
      layer: 'img_z',
      pid: 1,
      parent: {
        pid: 10,
        name: '天地图影像',
        icon: 'http://mars3d.cn/img/basemaps/tdt_img.png',
        type: 'group',
        layers: [
          {
            name: '底图',
            type: 'tdt',
            layer: 'img_d',
            pid: 1,
            id: 2,
            zIndex: 2,
          },
          {
            name: '注记',
            type: 'tdt',
            layer: 'img_z',
            pid: 1,
            id: 3,
            zIndex: 3,
          },
        ],
        id: 1,
      },
      id: 3,
      zIndex: 3,
    },
    高德注记: {
      name: '注记',
      type: 'gaode',
      layer: 'img_z',
      pid: 7,
      parent: {
        pid: 10,
        name: '高德影像',
        type: 'group',
        icon: 'http://mars3d.cn/img/basemaps/gaode_img.png',
        layers: [
          {
            name: '底图',
            type: 'gaode',
            layer: 'img_d',
            pid: 7,
            id: 8,
            zIndex: 6,
          },
          {
            name: '注记',
            type: 'gaode',
            layer: 'img_z',
            pid: 7,
            id: 9,
            zIndex: 7,
          },
        ],
        id: 7,
      },
      id: 9,
      zIndex: 7,
    },
  };
  return {
    baseMap: baseMaps[baseMapName],
    note: noteMaps[noteName],
  };
};
export default function fun(): any {
  const mapOptions = {
    scene: {
      // center: {
      //      lat: 36.495111,
      //      lng: 115.936283,
      //      alt: 1424675,
      //      heading: 359,
      //      pitch: -79,
      // },
      extent: {
        xmin: 105,
        xmax: 127,
        ymin: 30,
        ymax: 45,
      },
    },
    terrain: {
      url: 'http://data.mars3d.cn/terrain',
      show: true,
    },
    basemaps: [
      {
        pid: 10,
        name: '天地图影像',
        icon: 'http://mars3d.cn/img/basemaps/tdt_img.png',
        type: 'group',
        // show: 'true',
        layers: [
          {
            name: '底图',
            type: 'tdt',
            layer: 'img_d',
            pid: 1,
            parent: {
              pid: 10,
              name: '天地图影像',
              icon: 'http://mars3d.cn/img/basemaps/tdt_img.png',
              type: 'group',
              layers: [
                {
                  name: '底图',
                  type: 'tdt',
                  layer: 'img_d',
                  pid: 1,
                  id: 2,
                  zIndex: 2,
                },
                {
                  name: '注记',
                  type: 'tdt',
                  layer: 'img_z',
                  pid: 1,
                  id: 3,
                  zIndex: 3,
                },
              ],
              id: 1,
            },
            id: 2,
            zIndex: 2,
          },
          {
            name: '注记',
            type: 'tdt',
            layer: 'img_z',
            pid: 1,
            parent: {
              pid: 10,
              name: '天地图影像',
              icon: 'http://mars3d.cn/img/basemaps/tdt_img.png',
              type: 'group',
              layers: [
                {
                  name: '底图',
                  type: 'tdt',
                  layer: 'img_d',
                  pid: 1,
                  id: 2,
                  zIndex: 2,
                },
                {
                  name: '注记',
                  type: 'tdt',
                  layer: 'img_z',
                  pid: 1,
                  id: 3,
                  zIndex: 3,
                },
              ],
              id: 1,
            },
            id: 3,
            zIndex: 3,
          },
        ],
        id: 1,
        opacity: 1,
      },
      {
        pid: 10,
        name: '天地图电子',
        icon: 'http://mars3d.cn/img/basemaps/tdt_vec.png',
        type: 'group',
        layers: [
          {
            name: '底图',
            type: 'tdt',
            layer: 'vec_d',
            pid: 4,
            parent: {
              pid: 10,
              name: '天地图电子',
              icon: 'http://mars3d.cn/img/basemaps/tdt_vec.png',
              type: 'group',
              layers: [
                {
                  name: '底图',
                  type: 'tdt',
                  layer: 'vec_d',
                  pid: 4,
                  id: 5,
                  zIndex: 4,
                },
                {
                  name: '注记',
                  type: 'tdt',
                  layer: 'vec_z',
                  pid: 4,
                  id: 6,
                  zIndex: 5,
                },
              ],
              id: 4,
            },
            id: 5,
            zIndex: 4,
          },
          {
            name: '注记',
            type: 'tdt',
            layer: 'vec_z',
            pid: 4,
            parent: {
              pid: 10,
              name: '天地图电子',
              icon: 'http://mars3d.cn/img/basemaps/tdt_vec.png',
              type: 'group',
              layers: [
                {
                  name: '底图',
                  type: 'tdt',
                  layer: 'vec_d',
                  pid: 4,
                  id: 5,
                  zIndex: 4,
                },
                {
                  name: '注记',
                  type: 'tdt',
                  layer: 'vec_z',
                  pid: 4,
                  id: 6,
                  zIndex: 5,
                },
              ],
              id: 4,
            },
            id: 6,
            zIndex: 5,
          },
        ],
        id: 4,
        opacity: 1,
      },
      {
        pid: 10,
        name: '高德影像',
        type: 'group',
        icon: 'http://mars3d.cn/img/basemaps/gaode_img.png',
        layers: [
          {
            name: '底图',
            type: 'gaode',
            layer: 'img_d',
            pid: 7,
            parent: {
              pid: 10,
              name: '高德影像',
              type: 'group',
              icon: 'http://mars3d.cn/img/basemaps/gaode_img.png',
              layers: [
                {
                  name: '底图',
                  type: 'gaode',
                  layer: 'img_d',
                  pid: 7,
                  id: 8,
                  zIndex: 6,
                },
                {
                  name: '注记',
                  type: 'gaode',
                  layer: 'img_z',
                  pid: 7,
                  id: 9,
                  zIndex: 7,
                },
              ],
              id: 7,
            },
            id: 8,
            zIndex: 6,
          },
          {
            name: '注记',
            type: 'gaode',
            layer: 'img_z',
            pid: 7,
            parent: {
              pid: 10,
              name: '高德影像',
              type: 'group',
              icon: 'http://mars3d.cn/img/basemaps/gaode_img.png',
              layers: [
                {
                  name: '底图',
                  type: 'gaode',
                  layer: 'img_d',
                  pid: 7,
                  id: 8,
                  zIndex: 6,
                },
                {
                  name: '注记',
                  type: 'gaode',
                  layer: 'img_z',
                  pid: 7,
                  id: 9,
                  zIndex: 7,
                },
              ],
              id: 7,
            },
            id: 9,
            zIndex: 7,
          },
        ],
        id: 7,
        opacity: 1,
      },
      {
        pid: 10,
        name: '高德电子',
        type: 'gaode',
        icon: 'http://mars3d.cn/img/basemaps/gaode_vec.png',
        layer: 'vec',
        id: 11,
        opacity: 1,
        zIndex: 8,
      },
      {
        pid: 10,
        name: '百度影像',
        type: 'group',
        icon: 'http://mars3d.cn/img/basemaps/bd-img.png',
        layers: [
          {
            name: '底图',
            type: 'baidu',
            layer: 'img_d',
            pid: 12,
            parent: {
              pid: 10,
              name: '百度影像',
              type: 'group',
              icon: 'http://mars3d.cn/img/basemaps/bd-img.png',
              layers: [
                {
                  name: '底图',
                  type: 'baidu',
                  layer: 'img_d',
                  pid: 12,
                  id: 13,
                  zIndex: 9,
                },
                {
                  name: '注记',
                  type: 'baidu',
                  layer: 'img_z',
                  pid: 12,
                  id: 14,
                  zIndex: 10,
                },
              ],
              id: 12,
            },
            id: 13,
            zIndex: 9,
          },
          {
            name: '注记',
            type: 'baidu',
            layer: 'img_z',
            pid: 12,
            parent: {
              pid: 10,
              name: '百度影像',
              type: 'group',
              icon: 'http://mars3d.cn/img/basemaps/bd-img.png',
              layers: [
                {
                  name: '底图',
                  type: 'baidu',
                  layer: 'img_d',
                  pid: 12,
                  id: 13,
                  zIndex: 9,
                },
                {
                  name: '注记',
                  type: 'baidu',
                  layer: 'img_z',
                  pid: 12,
                  id: 14,
                  zIndex: 10,
                },
              ],
              id: 12,
            },
            id: 14,
            zIndex: 10,
          },
        ],
        id: 12,
        opacity: 1,
      },
      {
        pid: 10,
        name: '百度电子',
        icon: 'http://mars3d.cn/img/basemaps/bd-vec.png',
        type: 'baidu',
        layer: 'vec',
        id: 15,
        opacity: 1,
        zIndex: 11,
      },
      {
        pid: 10,
        name: '腾讯影像',
        icon: 'http://mars3d.cn/img/basemaps/tencent_img.png',
        type: 'group',
        layers: [
          {
            name: '底图',
            type: 'tencent',
            layer: 'img_d',
            pid: 16,
            parent: {
              pid: 10,
              name: '腾讯影像',
              icon: 'http://mars3d.cn/img/basemaps/tencent_img.png',
              type: 'group',
              layers: [
                {
                  name: '底图',
                  type: 'tencent',
                  layer: 'img_d',
                  pid: 16,
                  id: 17,
                  zIndex: 12,
                },
                {
                  name: '注记',
                  type: 'tencent',
                  layer: 'img_z',
                  pid: 16,
                  id: 18,
                  zIndex: 13,
                },
              ],
              id: 16,
            },
            id: 17,
            zIndex: 12,
          },
          {
            name: '注记',
            type: 'tencent',
            layer: 'img_z',
            pid: 16,
            parent: {
              pid: 10,
              name: '腾讯影像',
              icon: 'http://mars3d.cn/img/basemaps/tencent_img.png',
              type: 'group',
              layers: [
                {
                  name: '底图',
                  type: 'tencent',
                  layer: 'img_d',
                  pid: 16,
                  id: 17,
                  zIndex: 12,
                },
                {
                  name: '注记',
                  type: 'tencent',
                  layer: 'img_z',
                  pid: 16,
                  id: 18,
                  zIndex: 13,
                },
              ],
              id: 16,
            },
            id: 18,
            zIndex: 13,
          },
        ],
        id: 16,
        opacity: 1,
      },
      {
        pid: 10,
        name: '腾讯电子',
        icon: 'http://mars3d.cn/img/basemaps/tencent_vec.png',
        type: 'tencent',
        layer: 'vec',
        id: 19,
        opacity: 1,
        zIndex: 14,
      },
      {
        pid: 10,
        name: 'ArcGIS影像',
        icon: 'http://mars3d.cn/img/basemaps/esriWorldImagery.png',
        type: 'xyz',
        url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
        enablePickFeatures: false,
        id: 21,
        templateValues: {
          dataServer: '//data.mars3d.cn',
          gltfServerUrl: '//data.mars3d.cn/gltf',
        },
        opacity: 1,
        zIndex: 15,
      },
      {
        pid: 10,
        name: '微软影像',
        icon: 'http://mars3d.cn/img/basemaps/bingAerial.png',
        type: 'bing',
        layer: 'Aerial',
        id: 22,
        opacity: 1,
        zIndex: 16,
      },
      {
        id: 2017,
        pid: 10,
        name: '暗色底图',
        type: 'gaode',
        icon: 'http://mars3d.cn/img/basemaps/blackMarble.png',
        layer: 'vec',
        invertColor: true,
        filterColor: '#4e70a6',
        brightness: 0.6,
        contrast: 1.8,
        gamma: 0.3,
        hue: 1,
        saturation: 0,
        opacity: 1,
        zIndex: 17,
      },
      {
        pid: 10,
        name: '蓝色底图',
        icon: 'http://mars3d.cn/img/basemaps/bd-c-midnight.png',
        type: 'xyz',
        url: 'http://map.geoq.cn/arcgis/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}',
        chinaCRS: 'GCJ02',
        enablePickFeatures: false,
        id: 23,
        templateValues: {
          dataServer: '//data.mars3d.cn',
          gltfServerUrl: '//data.mars3d.cn/gltf',
        },
        opacity: 1,
        zIndex: 18,
      },
      {
        pid: 10,
        name: '黑色底图',
        icon: 'http://mars3d.cn/img/basemaps/bd-c-dark.png',
        type: 'tencent',
        layer: 'custom',
        style: '4',
        id: 24,
        opacity: 1,
        zIndex: 19,
      },

      {
        id: 2023,
        pid: 10,
        name: '无底图',
        icon: 'http://mars3d.cn/img/basemaps/null.png',
        type: 'grid',
        color: '#ffffff',
        alpha: 0.03,
        cells: 2,
        opacity: 0.03,
        zIndex: 22,
      },
      {
        pid: 10,
        name: '星图影像',
        icon: 'http://mars3d.cn/img/basemaps/tdt_img.png',
        type: 'group',
        layers: [
          {
            name: '底图',
            type: 'xyz',
            url: 'https://tiles{s}.geovisearth.com/base/v1/img/{z}/{x}/{y}?token=82455ef06c72bb3a35bbb4d7d05fd9eceb96a94dc942a056b8feb0e5928ed96f',
            subdomains: '123',
          },
          {
            name: '注记',
            type: 'xyz',
            url: 'https://tiles{s}.geovisearth.com/base/v1/cia/{z}/{x}/{y}?token=82455ef06c72bb3a35bbb4d7d05fd9eceb96a94dc942a056b8feb0e5928ed96f',
            subdomains: '123',
          },
        ],
      },
      {
        pid: 10,
        name: '星图电子',
        icon: 'http://mars3d.cn/img/basemaps/offline.png',
        type: 'xyz',
        url: 'https://tiles{s}.geovisearth.com/base/v1/vec/{z}/{x}/{y}?token=82455ef06c72bb3a35bbb4d7d05fd9eceb96a94dc942a056b8feb0e5928ed96f',
        subdomains: '123',
      },
    ],
    layers: [],
    control: {
      toolbar: {
        position: 'right-bottom',
      },
      baseLayerPicker: true,
      homeButton: true,
      sceneModePicker: true,
      vrButton: false,
      fullscreenButton: false,
      navigationHelpButton: false,
      animation: false,
      timeline: false,
      infoBox: false,
      geocoder: false,
      selectionIndicator: false,
      showRenderLoopErrors: true,
      contextmenu: { hasDefault: true },
      mouseDownView: true,
      zoom: { insertIndex: 1 },
      // compass: { bottom: '410px', right: '2px' },
      distanceLegend: { left: '100px', bottom: '2px' },
      locationBar: {
        crs: 'CGCS2000_GK_Zone_3',
        crsDecimal: 0,
        show: false,
        template:
          "<div>经度:{lng}</div> <div>纬度:{lat}</div> <div class='hide1000'>横{crsx}  纵{crsy}</div> <div>海拔：{alt}米</div> <div class='hide700'>层级：{level}</div><div>方向：{heading}°</div> <div>俯仰角：{pitch}°</div><div class='hide700'>视高：{cameraHeight}米</div>帧率：{fps}帧</div>",
      },
    },
  };
  const initMap = (dom: any, val = {}) => {
    let map: any = null;
    const options: any = { ...mapOptions, ...val };
    console.log('mars3d', mars3d);
    map = new mars3d.Map(dom, options);
    return map;
  };
  const animation = (mapData: any) => {
    mapData.openFlyAnimation({
      callback() {},
    });
  };
  const flyToLayer = (mapData: any, id: any) => {
    mapData.getLayer(id).flyTo();
  };
  // 飞到指定位置
  const setPosition = (map: any, coord: any) => {
    const { lat, lng, alt = 100, roll = 0, pitch = -90, heading = 0 } = coord;
    const pos = { lat, lng, alt, roll, pitch, heading };
    map.setCameraView(pos, {
      duration: 1.6,
    });
  };
  // 飞到指定范围
  const FlytoRectangle = (
    map: any,
    west: any,
    south: any,
    east: any,
    north: any,
  ) => {
    const ext = mars3d.Cesium.Rectangle.fromDegrees(west, south, east, north);
    const op = {};
    map.flyToExtent(ext, op);
  };
  // 飞行到指定范围
  const mapFlytoExent = (map: any, extent: any) => {
    const exent = {
      xmin: Number(extent.xmin),
      xmax: Number(extent.xmax),
      ymin: Number(extent.ymin),
      ymax: Number(extent.ymax),
    };
    map.flyToExtent(exent, {});
  };
  // 根据geometry 获取指定类型 并移动到指定位置
  const getGemoToFly = (map: any, geometry: any) => {
    const features: any =
      typeof geometry === 'string' ? WKT.parse(geometry) : geometry;
    if (features.type === 'Point') {
      const coord = {
        lat: features.coordinates[1],
        lng: features.coordinates[0],
      };
      setPosition(map, coord);
    } else if (features.type === 'LineString') {
      // 如果是三维数组 改成二维数组
      if (features.coordinates[0][0][0]) {
        features.coordinates = features.coordinates.flat();
      }
      const mpt: any = mars3d.LngLatPoint.fromCartesian(
        mars3d.PolyUtil.centerOfMass(features.coordinates as any),
      );
      // console.log(mpt, features)
      const coord = {
        lat: mpt.lat,
        lng: mpt.lng,
      };
      setPosition(map, coord);
    }
  };
  // 添加千米表矢量
  const addKmFeature = (mapData: any, kmlList: any, layerId: string) => {
    const KLMTLayers = mapData.getLayerById(layerId);
    const labelList: any = [];
    kmlList.forEach((item: any) => {
      const graphic = new mars3d.graphic.LabelPrimitive({
        position: [item.lon, item.lat],

        style: {
          text: item.notes,
          font_size: 30,
          color: '#bb1e3f',
          distanceDisplayCondition: true,
          distanceDisplayCondition_far: 50_000,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          scaleByDistance: new Cesium.NearFarScalar(10_000, 0.5, 500_000, 0.1),
          background: true,
          backgroundColor: 'rgba(255,255,255,0.8)',
          stroke: true,
          strokeColor: 'rgba(0,0,0,0.5)',
          backgroundPadding: 10,
          // clampToGround: true
        },
        // clampToTileset: true,
        frameRateHeight: 30,
      });
      labelList.push(graphic);
    });
    KLMTLayers.addGraphic(labelList);
  };
  // 添加矢量图层
  const addFeatureLayers = (map: any, layers: any) => {
    layers.forEach((item: any) => {
      const layerOptions: any = {
        ...item,
        id: item.id,
        name: item.name,
        show: item.show,
      };
      let layer = null;
      switch (item.type) {
        case 'GeoJsonLayer': {
          layer = new mars3d.layer.GeoJsonLayer({
            ...layerOptions,
          });

          break;
        }
        case 'GraphicLayer': {
          layer = new mars3d.layer.GraphicLayer({
            ...layerOptions,
          });

          break;
        }
        case 'TilesetLayer': {
          // layer = new mars3d.layer.TilesetLayer({ ...layerOptions })

          break;
        }
        case 'XyzLayer': {
          layer = new mars3d.layer.XyzLayer({
            ...layerOptions,
            url: '',
          });

          break;
        }
        // No default
      }
      layer && map.addLayer(layer);
    });
  };
  // 新增相机点位
  /**
   * 添加点设备特征图
   * @param position - 设备位置坐标
   * @param featureData - 设备特征数据对象，包含在线状态等信息
   * @param labelText - 设备标签文本
   * @returns 返回创建的mars3d图形对象
   * @description 根据设备在线状态创建不同样式的标记点图形，包含图标、标签和状态显示
   */
  const addPointCameraFeature = (
    options: any,
    featureData: any,
    labelText: string,
  ) => {
    let graphic = null;
    const imgUrl = `./img/mapPages/摄像机.png`;
    graphic = new mars3d.graphic.BillboardPrimitive({
      ...options,
      style: {
        image: imgUrl,
        scale: 0.2,
        clampToGround: true,
        distanceDisplayCondition: true,
        distanceDisplayCondition_far: 400_000,
        pixelOffsetY: 0,
        label: {
          visibleDepth: true,
          text: labelText,
          font_size: 14,
          background: true, // 是否开启背景
          backgroundColor: 'rgba(2, 46, 87,0.5)', // 背景颜色
          backgroundPadding: 3,
          font_weight: 'bold',
          color: '#f3fe01',
          pixelOffsetY: -25,
          distanceDisplayCondition: true,
          distanceDisplayCondition_far: 400_000,
          distanceDisplayCondition_near: 0,
        },

        distanceDisplayPoint: {
          color: '#52c41a',
          pixelSize: 10,
          pixelOffsetY: -10,
          distanceDisplayCondition: true,
          distanceDisplayCondition_far: 5_000_000,
        },
      },
      attr: {
        ...featureData,
      },
    } as any);
    return graphic;
  };
  // 用户点
  const addPointUserFeature = (
    position: any,
    featureData: any,
    labelText: string,
  ) => {
    let graphic = null;
    let imgUrl = null;
    let graphicState = null;
    let pointColor = null;
    if (featureData.online) {
      imgUrl = `./img/mapPages/固定.png`;
      // graphicState = '固定'
      graphicState = '高精度';
      pointColor = '#13c2c2';
    } else {
      imgUrl = `./img/mapPages/非固定.png`;
      // graphicState = '非固定'
      graphicState = '低精度';
      pointColor = '#ff3c30';
    }
    graphic = new mars3d.graphic.BillboardPrimitive({
      position,
      name: graphicState,
      id: featureData.id,
      style: {
        image: imgUrl,
        scale: 0.5,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        distanceDisplayCondition: true,
        distanceDisplayCondition_far: 400_000,
        pixelOffsetY: -10,
        label: {
          visibleDepth: false,
          text: labelText,
          font_size: 15,
          background: true, // 是否开启背景
          backgroundColor: 'rgba(2, 46, 87,0.5)', // 背景颜色
          backgroundPadding: 6,
          font_weight: 'bold',
          color: '#f3fe01',
          pixelOffsetY: 10,
          distanceDisplayCondition: true,
          distanceDisplayCondition_far: 400_000,
          distanceDisplayCondition_near: 0,
        },
        distanceDisplayPoint: {
          color: pointColor,
          pixelSize: 10,
          pixelOffsetY: -10,
          distanceDisplayCondition: true,
          distanceDisplayCondition_far: 4_000_000,
        },
      },
      attr: {
        data: featureData,
        type: 'userPoint',
      },
    } as any);

    return graphic;
  };
  // 新增线
  const addLineFeature = (position: any, name: string, labelText: string) => {
    let graphic = null;
    graphic = new mars3d.graphic.PolylineEntity({
      positions: position,
      name,
      style: {
        width: 3,
        color: `#a0e478`,
        distanceDisplayCondition: true,
        distanceDisplayCondition_far: 4_000_000,
        distanceDisplayCondition_near: 0,
        label: {
          visibleDepth: false,
          text: labelText,
          font_size: 18,
          backgroundPadding: 6,
          font_weight: 'bold',
          backgroundColor: 'rgba(2, 46, 87,0.5)', // 背景颜色
          color: '#0070cb',
          pixelOffsetY: 10,
          distanceDisplayCondition: true,
          distanceDisplayCondition_far: 40_000,
          distanceDisplayCondition_near: 0,
        },
      },
      attr: {},
    } as any);
    return graphic;
  };
  // 根据图层id 清除图层上的所有要素
  const removeLayerFeature = (mapData: any, layersId: string, name: string) => {
    const layer = mapData.getLayerById(layersId);
    if (!layer) return;
    layer.getGraphicsByAttr(name, 'name').forEach((item: any) => {
      layer.removeGraphic(item);
    });
  };
  // 添加自定义工具
  const addToolButton = (map: any, callback: any) => {
    const measure = new mars3d.thing.Measure({
      name: 'measure',
      label: {
        color: '#ffffff',
        font_family: '楷体',
        font_size: 18,
        background: false,
      },
    });
    map.addThing(measure);
    const goobalViewButton = new mars3d.control.ToolButton({
      title: '全局视图',
      icon: './img/mapPages/全局视图.png',
      className: '',
      insertIndex: 1, // 插入的位置顺序, 1是home按钮后面
      click: () => {
        callback('layerManagementShow');
      },
    });
    map.addControl(goobalViewButton);

    const kjjlBtton = new mars3d.control.ToolButton({
      title: '水平距离',
      icon: './img/mapPages/水平距离.png',
      className: '',
      insertIndex: 2, // 插入的位置顺序, 1是home按钮后面
      click: () => {
        measure.distance({
          showAddText: true,
          label: {
            color: '#ffffff',
            font_family: '楷体',
            font_size: 18,
            background: true,
          },
        });
      },
    });
    map.addControl(kjjlBtton);

    const spmjBtton = new mars3d.control.ToolButton({
      title: '水平面积',
      icon: './img/mapPages/水平面积.png',
      className: '',
      insertIndex: 3, // 插入的位置顺序, 1是home按钮后面
      click: () => {
        measure.area({
          label: {
            color: '#ffffff',
            font_family: '楷体',
            font_size: 18,
            background: true,
          },
        });
      },
    });
    map.addControl(spmjBtton);
    const gcBtton = new mars3d.control.ToolButton({
      title: '高差',
      icon: './img/mapPages/高差.png',
      className: '',
      insertIndex: 4, // 插入的位置顺序, 1是home按钮后面
      click: () => {
        measure.heightTriangle({
          label: {
            color: '#ffffff',
            font_family: '楷体',
            font_size: 18,
            background: true,
          },
        });
      },
    });
    map.addControl(gcBtton);

    const removeBtton = new mars3d.control.ToolButton({
      title: '清除',
      icon: './img/mapPages/清除.png',
      className: '',
      insertIndex: 5, // 插入的位置顺序, 1是home按钮后面
      click: () => {
        measure.clear();
      },
    });
    map.addControl(removeBtton);
  };
  // 地图绑定鼠标悬浮事件
  const bindMapHover = (map: any, callback: any) => {
    let timer: any = null;
    map &&
      map.on('mouseMoveTarget', async (data: any) => {
        const coord: any = mars3d.PointTrans.cartesian2lonlat(data.cartesian);
        const obj = {
          lon: coord[0] ?? 0,
          lat: coord[1] ?? 0,
        };
        if (timer) {
          clearTimeout(timer);
        }
        timer = setTimeout(() => {
          callback(obj);
        }, 1000);
      });
  };

  const setLocationOption = (map: any, _val: any = '') => {
    const locationBar = mars3d.ControlUtil.create('locationBar' as any, {
      crs: 'CGCS2000_GK_Zone_3',
      crsDecimal: 0,
      template: `<div>经度:{lng}</div> <div>纬度:{lat}</div> <div class='hide1000'>横{crsx} 纵{crsy}</div> <div>海拔：{alt}米</div> <div class='hide700'>层级：{level}</div><div>方向：{heading}°</div> <div>俯仰角：{pitch}°</div><div class='hide700'>视高：{cameraHeight}米</div>帧率：{fps}帧</div>`,
    });
    map.addControl(locationBar);
  };
  const LimitCameraView = (map: any) => {
    const cameraHistory = new mars3d.thing.CameraHistory({
      limit: {
        // 限定视角范围
        position: Cesium.Cartesian3.fromDegrees(115.9, 38.9, 0),
        radius: 750_000,
        debugExtent: false,
      },
      maxCacheCount: 999,
    });
    map.addThing(cameraHistory);
  };
  // 全局视图 根据设备类型 设置显示隐藏
  const showFeature = (
    map: any,
    layerId: string,
    state: string,
    show: boolean,
  ) => {
    const layer = map.getLayerById(layerId);
    if (!layer) return;
    layer.getGraphicsByAttr(state, 'name').forEach((item: any) => {
      item.show = show;
    });
  };
  // 飞行指定feature 并且打开弹窗
  const flyToFeature = (map: any, layerId: string, featureId: any) => {
    const layer = map.getLayerById(layerId);
    if (!layer) return;
    const graphic = layer.getGraphicById(featureId);
    if (!graphic) return;
    graphic.flyTo({
      radius: 1000,
      duration: 1.5,
    });
    setTimeout(() => {
      graphic.openPopup();
    }, 1500);
  };
  const addTilesetLayer = (map: any, options: any) => {
    const tileset = new mars3d.layer.TilesetLayer({
      ...options,
      show: true,
      maximumScreenSpaceError: 16, // 【重要】数值加大，能让最终成像变模糊
      // cacheBytes: 1073741824, // 1024MB = 1024*1024*1024 【重要】额定显存大小(以字节为单位)，允许在这个值上下波动。
      // maximumCacheOverflowBytes: 2147483648, // 2048MB = 2048*1024*1024 【重要】最大显存大小(以字节为单位)。
      maximumMemoryUsage: 512, // 【cesium 1.107+弃用】内存建议显存大小的50%左右，内存分配变小有利于倾斜摄影数据回收，提升性能体验
      cullWithChildrenBounds: true,
      dynamicScreenSpaceError: false, // true时会在真正的全屏加载完之后才清晰化模型
      dynamicScreenSpaceErrorDensity: 0.002_78,
      dynamicScreenSpaceErrorFactor: 4,
      dynamicScreenSpaceErrorHeightFalloff: 0.25,
      skipLevelOfDetail: true, // 是Cesium在1.5x 引入的一个优化参数，这个参数在金字塔数据加载中，可以跳过一些级别，这样整体的效率会高一些，数据占用也会小一些。但是带来的异常是：1） 加载过程中闪烁，看起来像是透过去了，数据载入完成后正常。2，有些异常的面片，这个还是因为两级LOD之间数据差异较大，导致的。当这个参数设置false，两级之间的变化更平滑，不会跳跃穿透，但是清晰的数据需要更长，而且还有个致命问题，一旦某一个tile数据无法请求到或者失败，导致一直不清晰。所以我们建议：对于网络条件好，并且数据总量较小的情况下，可以设置false，提升数据显示质量。
      preferLeaves: true,
      baseScreenSpaceError: 1024,
      skipScreenSpaceErrorFactor: 16,
      skipLevels: 1,
      immediatelyLoadDesiredLevelOfDetail: false,
      loadSiblings: false, // 如果为true则不会在已加载完模型后，自动从中心开始超清化模型
      // cullRequestsWhileMoving: true,
      // cullRequestsWhileMovingMultiplier: 10,
      // progressiveResolutionHeightFraction: 0.5, //【重要】 数值偏于0能够让初始加载变得模糊
      luminanceAtZenith: 0.2,
      preloadWhenHidden: true,
      foveatedScreenSpaceError: true,
      showOutline: false,
      enableShowOutline: false,
      templateValues: {},
      flood: {
        precise: false,
        enabled: true,
      },
      attr: {},
    });
    map.addLayer(tileset);
  };
  const addImageLayer = (map: any, options: any) => {
    const imageLayer = new mars3d.layer.XyzLayer({
      ...options,
    });
    map.addLayer(imageLayer);
  };
  // 给指定图层添加点击事件
  const addlayersEventClick = (map: any, layerId: string, callBack: any) => {
    const layer = map.getLayerById(layerId);
    if (!layer) return;
    layer.on('click', (event: any) => {
      callBack(event);
    });
  };

  return {
    mapOptions,
    showFeature,
    addPointCameraFeature,
    addPointUserFeature,
    animation,
    initMap,
    flyToLayer,
    setPosition,
    FlytoRectangle,
    mapFlytoExent,
    getUserPreferencesLayers,
    getGemoToFly,
    addKmFeature,
    addFeatureLayers,
    addToolButton,
    removeLayerFeature,
    setLocationOption,
    bindMapHover,
    LimitCameraView,
    flyToFeature,
    addLineFeature,
    addTilesetLayer,
    addImageLayer,
    addlayersEventClick,
  };
}
